package com.example.demo.Controller;

import com.example.demo.pojo.Cart;
import com.example.demo.pojo.CartItem;
import com.example.demo.pojo.Member;
import com.example.demo.pojo.Order;
import com.example.demo.service.orderService.OrderService;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.math.BigDecimal;
import java.sql.Date;
import java.time.*;

import java.util.HashMap;
import java.util.UUID;

@Controller
@RequestMapping("/order")
public class OrderController {
    @Resource
    OrderService orderService ;

    @GetMapping("/toOrder")
    public  String toOrder(HttpServletRequest request, Model model){
        LocalDateTime currentTime = LocalDateTime.now();
        // 提取LocalDate
        LocalDate localDate = currentTime.toLocalDate();
        // 转换为java.sql.Date
        java.sql.Date sqlDate = Date.valueOf(localDate);
        String order = ""+System.currentTimeMillis();
        model.addAttribute("orderId",order);
        request.getSession().setAttribute("orderId",order);
        model.addAttribute("time",currentTime);
        Order order1 = new Order();
        order1.setCreateTime(sqlDate);
        order1.setId(order);
        order1.setPrice(new BigDecimal(request.getSession().getAttribute("CartTotalPrice").toString()));
        Member member =(Member) request.getSession().getAttribute("member");
        if (member!=null){
            order1.setMemberId(member.getId());
        }
        order1.setStatus(new Byte("1"));
        orderService.saveOrder(order1);

        return "order";
    }


    @GetMapping("/toshow")
    @Transactional
    public  String toshow(HttpSession session ,Model model){
        if (session.getAttribute("toshowVisited") != null) {
            // 如果已经访问过，直接跳转到checkout页面
            return "checkout";
        }
        Cart cart = (Cart) session.getAttribute("cart");
        HashMap<Integer, CartItem> items = cart.getItems();
        for (Integer integer : items.keySet()) {
            CartItem cartItem = items.get(integer);
            Integer count = cartItem.getCount();
            Integer id = cartItem.getId();
            orderService.UpdateSalesAndStock(id,count);

        }
        // 标记为已访问
        session.setAttribute("toshowVisited", true);

        return "checkout";
    }

}
